import axios from "axios";
import { showLoading, hideLoading } from "@/utils/loading";
import { ElMessage } from "element-plus";
class HttpRequest {
  constructor(options = {}) {
    this.instance = axios.create(options);
    this.instance.interceptors.request.use(
      (config) => {
        // 在发送请求之前做些什么
        const token = window.localStorage.getItem("token");
        if (token) {
          config.headers.token = token;
        }
        // 请求拦截进来调用显示loading效果
        showLoading();
        return config;
      },
      (err) => {
        Promise.reject(err);
      }
    );
    this.instance.interceptors.response.use(
      (res) => {
        // console.log("interceptors: ", res);
        // 响应拦截进来隐藏loading效果，此处采用延时处理是合并loading请求效果，避免多次请求loading关闭又开启
        setTimeout(() => {
          hideLoading();
        }, 200);
        const code = res.data.code;
        if (code) {
          ElMessage.error(res.data.msg);
          if (code === 400) {
            // 无效的token或者token已经过期~
            window.localStorage.removeItem("token", "");
            window.localStorage.removeItem("userInfo", "");
            window.localStorage.removeItem("userRule", "");
            return;
          }
        }
        return res.data.data;
        //   if () {}
      },
      (err) => {
        // 响应拦截进来隐藏loading效果，此处采用延时处理是合并loading请求效果，避免多次请求loading关闭又开启
        setTimeout(() => {
          hideLoading();
        }, 200);

        return Promise.reject(err);
      }
    );
  }
  request(opt = {}) {
    return this.instance.request(opt);
  }
  post(data = {}) {
    return this.instance.request({
      ...data,
      method: "post",
    });
  }
  get(data = {}) {
    return this.instance.request({
      ...data,
      method: "get",
    });
  }
}

export default new HttpRequest({
  baseURL: "/api",
  timeout: 5000,
});
